// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'

const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/Login.vue')
    },
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/subscription',
        name: 'Subscription',
        component: () => import('../views/Subscription.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/nodes',
        name: 'Nodes',
        component: () => import('../views/Nodes.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/usage',
        name: 'Usage',
        component: () => import('../views/Usage.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/',
        redirect: '/dashboard'
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('access_token')

    // 检查token有效性（简单验证）
    const isTokenValid = token && token.length > 10 // 简单长度验证

    if (to.meta.requiresAuth && !isTokenValid) {
        next('/login')
    } else if (to.name === 'Login' && isTokenValid) {
        // 如果已登录，跳转到仪表板
        next('/dashboard')
    } else {
        next()
    }
})

export default router